#include "EpollSvr.hpp"

#define CHECK_RET(p) if(p != true){return -1;}

int main()
{
    TcpSvr listen_ts;
    CHECK_RET(listen_ts.CreateSocket());
    CHECK_RET(listen_ts.Bind("0.0.0.0", 19999));
    CHECK_RET(listen_ts.Listen());

    EpollSvr es;
    CHECK_RET(es.InitSvr());
    es.AddFd(listen_ts.GetFd());

    while(1)
    {
        //1.监控
        std::vector<TcpSvr> vec;
        if(!es.EpollWait(&vec))
        {
            continue;
        }

        for(size_t i = 0; i < vec.size(); i++)
        {
            //区分一下文件描述符是否是侦听套接字
            if(vec[i].GetFd() == listen_ts.GetFd())
            {
                //获取新连接
                TcpSvr peerts;
                struct sockaddr_in peeraddr;
                listen_ts.Accept(&peerts, &peeraddr);
                printf("Hava a new connection : ip=[%s], port=[%d]\n", inet_ntoa(peeraddr.sin_addr), ntohs(peeraddr.sin_port));
                //将新连接对应的文件描述符添加到epoll当中
                es.AddFd(peerts.GetFd());
            }
            else
            {
                std::string data;
                bool ret = vec[i].Recv(&data);
                if(!ret)
                {
                    es.DeleteFd(vec[i].GetFd());
                    vec[i].Close();
                }

                printf("client say: %s\n", data.c_str());
                //回复数据
            }
        }
    }
    return 0;
}
